package com.xiong.excel.listener;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.xiong.excel.constant.SystemConstants;
import com.xiong.excel.pojo.PurchaseContract;
import com.xiong.excel.utils.BigDecimalCount;
import com.xiong.excel.utils.ConvertUpMoney;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * @author XiongDa
 */
@Slf4j
public class PurchaseContractListener extends AnalysisEventListener<PurchaseContract> {

    int i = 0;
    int j = 0;

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 50;

    private List<PurchaseContract> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(PurchaseContract data, AnalysisContext context) {

        log.info("解析到第：{} 条数据:{}", ++j, JSON.toJSONString(data));

        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData(cachedDataList);
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

    }

    /**
     * 加上存储数据库
     */
    private void saveData(List<PurchaseContract> cachedDataList ) {

        log.info("{} 条数据，开始导出！", cachedDataList.size());

        for (PurchaseContract purchaseContract : cachedDataList) {

            if("熊林妹".equals(purchaseContract.getName())) {

                log.info("{} 第:{} 条数据，开始导出===================================================", purchaseContract.getName(), ++i);

                //大写金额转换  实际金额  3,123 => 叁千壹佰贰十叁元
                String actualAmount = purchaseContract.getActualAmount().replace(",", "");
                purchaseContract.setActualAmount(actualAmount);
                purchaseContract.setActualAmountUp(ConvertUpMoney.toChinese(actualAmount));

                //计原合同金额
                String originalAmount = purchaseContract.getOriginalAmount().replace(",", "");
                purchaseContract.setOriginalAmount(originalAmount);

                //变更金额    变更金额 = 实际金额-原合同金额
                String changeAmount = BigDecimalCount.BigDecimalCal(actualAmount, "-", originalAmount);
                purchaseContract.setChangeAmount(changeAmount);

                //导出目录 和文件名配置
                //去除 / 符合导致bug   文件名字包含 / 会导致创建下一级目录, 所以把 / 替换成 - 符号
                String fileName = (purchaseContract.getSupplier() + purchaseContract.getContractId() + purchaseContract.getProject() + ".xls").replace("/", "-");
                String targetFileName = SystemConstants.TARGET_FILE_NAME + fileName;

                System.out.println("--------------------------------------------------------------------");
                System.out.println(purchaseContract);
                System.out.println("---------------------------------------------------------------------");
                // 这里 会填充到第一个sheet， 然后文件流会自动关闭
                EasyExcel.write(targetFileName).withTemplate(SystemConstants.TEMPLATE_FILE_NAME).sheet().doFill(purchaseContract);
            }
        }
        log.info("{} 条数据，导出完成！=============================================================", cachedDataList.size());
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        log.info("解析到一条头数据:{}", JSON.toJSONString(headMap));
        // 如果想转成成 Map<Integer,String>
        // 方案1： 不要implements ReadListener 而是 extends AnalysisEventListener
        // 方案2： 调用 ConverterUtils.convertToStringMap(headMap, context) 自动会转换
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData(cachedDataList);
        log.info("所有数据解析完成！");
    }


}